#ifndef JFUTUREINTERFACE_H
#define JFUTUREINTERFACE_H

#include "jconcurrent_global.h"
#include "jconcurrentexception.h"
#include "jconcurrentresultstore.h"
#include "jmutex.h"
#include "jrunnable.h"
#include <vector>
#include <string>
#include <list>

template <typename T> class JFuture;
class JFutureInterfaceBasePrivate;
class JFutureWatcherBase;
class JFutureWatcherBasePrivate;

class JCONCURRENT_EXPORT JFutureInterfaceBase
{
public:
    enum State {
        NoState   = 0x00,
        Running   = 0x01,
        Started   = 0x02,
        Finished  = 0x04,
        Canceled  = 0x08,
        Paused    = 0x10,
        Throttled = 0x20
    };

    JFutureInterfaceBase(State initialState = NoState);
    JFutureInterfaceBase(const JFutureInterfaceBase &other);
    virtual ~JFutureInterfaceBase();

    // reporting functions available to the engine author:
    void reportStarted();
    void reportFinished();
    void reportCanceled();
    void reportException(const JConcurrent::Exception &e);
    void reportResultsReady(int beginIndex, int endIndex);

    void setRunnable(JRunnable *runnable);
    void setFilterMode(bool enable);
    void setProgressRange(int minimum, int maximum);
    int progressMinimum() const;
    int progressMaximum() const;
    bool isProgressUpdateNeeded() const;
    void setProgressValue(int progressValue);
    int progressValue() const;
    void setProgressValueAndText(int progressValue, const jstring &progressText);
    jstring progressText() const;

    void setExpectedResultCount(int resultCount);
    int expectedResultCount();
    int resultCount() const;

    bool queryState(State state) const;
    bool isRunning() const;
    bool isStarted() const;
    bool isCanceled() const;
    bool isFinished() const;
    bool isPaused() const;
    bool isThrottled() const;
    bool isResultReadyAt(int index) const;

    void cancel();
    void setPaused(bool paused);
    void togglePaused();
    void setThrottled(bool enabled);

    void waitForFinished();
    bool waitForNextResult();
    void waitForResult(int resultIndex);
    void waitForResume();

    JMutex *mutex() const;
    JConcurrent::internal::ExceptionStore &exceptionStore();
    JConcurrent::ResultStoreBase &resultStoreBase();
    const JConcurrent::ResultStoreBase &resultStoreBase() const;

    inline bool operator==(const JFutureInterfaceBase &other) const { return d == other.d; }
    inline bool operator!=(const JFutureInterfaceBase &other) const { return d != other.d; }
    JFutureInterfaceBase &operator=(const JFutureInterfaceBase &other);

protected:
    bool referenceCountIsOne() const;

private:
    JFutureInterfaceBasePrivate *d;

private:
    friend class JFutureWatcherBase;
    friend class JFutureWatcherBasePrivate;
};

template <typename T>
class JFutureInterface : public JFutureInterfaceBase
{
public:
    JFutureInterface(State initialState = NoState)
        : JFutureInterfaceBase(initialState)
    { }
    JFutureInterface(const JFutureInterface &other)
        : JFutureInterfaceBase(other)
    { }
    ~JFutureInterface()
    {
        if (referenceCountIsOne()) {
            resultStore().clear();
        }
    }

    static JFutureInterface canceledResult()
    { return JFutureInterface(State(Started | Finished | Canceled)); }

    JFutureInterface &operator=(const JFutureInterface &other)
    {
        if (referenceCountIsOne()) {
            resultStore().clear();
        }
        JFutureInterfaceBase::operator=(other);
        return *this;
    }

    inline JFuture<T> future(); // implemented in jfuture.h

    inline void reportResult(const T *result, int index = -1);
    inline void reportResult(const T &result, int index = -1);
    inline void reportResults(const jvector<T> &results, int beginIndex = -1, int count = -1);
    inline void reportFinished(const T *result = 0);

    inline const T &resultReference(int index) const;
    inline const T *resultPointer(int index) const;
    inline jlist<T> results();

private:
    JConcurrent::ResultStore<T> &resultStore()
    { return static_cast<JConcurrent::ResultStore<T> &>(resultStoreBase()); }
    const JConcurrent::ResultStore<T> &resultStore() const
    { return static_cast<const JConcurrent::ResultStore<T> &>(resultStoreBase()); }
};

template <typename T>
inline void JFutureInterface<T>::reportResult(const T *result, int index)
{
    JMutexLocker locker(mutex());
    if (this->queryState(Canceled) || this->queryState(Finished)) {
        return;
    }

    JConcurrent::ResultStore<T> &store = resultStore();

    if (store.filterMode()) {
        const int resultCountBefore = store.count();
        store.addResult(index, result);
        this->reportResultsReady(resultCountBefore, resultCountBefore + store.count());
    } else {
        const int insertIndex = store.addResult(index, result);
        this->reportResultsReady(insertIndex, insertIndex + 1);
    }
}

template <typename T>
inline void JFutureInterface<T>::reportResult(const T &result, int index)
{
    reportResult(&result, index);
}

template <typename T>
inline void JFutureInterface<T>::reportResults(const jvector<T> &_results, int beginIndex, int count)
{
    JMutexLocker locker(mutex());
    if (this->queryState(Canceled) || this->queryState(Finished)) {
        return;
    }

    JConcurrent::ResultStore<T> &store = resultStore();

    if (store.filterMode()) {
        const int resultCountBefore = store.count();
        store.addResults(beginIndex, &_results, count);
        this->reportResultsReady(resultCountBefore, store.count());
    } else {
        const int insertIndex = store.addResults(beginIndex, &_results, count);
        this->reportResultsReady(insertIndex, insertIndex + _results.size());
    }
}

template <typename T>
inline void JFutureInterface<T>::reportFinished(const T *result)
{
    if (result) {
        reportResult(result);
    }
    JFutureInterfaceBase::reportFinished();
}

template <typename T>
inline const T &JFutureInterface<T>::resultReference(int index) const
{
    JMutexLocker lock(mutex());
    return resultStore().resultAt(index).value();
}

template <typename T>
inline const T *JFutureInterface<T>::resultPointer(int index) const
{
    JMutexLocker lock(mutex());
    return resultStore().resultAt(index).pointer();
}

template <typename T>
inline jlist<T> JFutureInterface<T>::results()
{
    if (this->isCanceled()) {
        exceptionStore().throwPossibleException();
        return jlist<T>();
    }
    JFutureInterfaceBase::waitForResult(-1);

    jlist<T> res;
    JMutexLocker lock(mutex());

    JConcurrent::ResultIterator<T> it = resultStore().begin();
    while (it != resultStore().end()) {
        res.push_back(it.value());
        ++it;
    }

    return res;
}

template <>
class JFutureInterface<void> : public JFutureInterfaceBase
{
public:
    JFutureInterface<void>(State initialState = NoState)
        : JFutureInterfaceBase(initialState)
    { }
    JFutureInterface<void>(const JFutureInterface<void> &other)
        : JFutureInterfaceBase(other)
    { }

    static JFutureInterface<void> canceledResult()
    { return JFutureInterface(State(Started | Finished | Canceled)); }

    JFutureInterface<void> &operator=(const JFutureInterface<void> &other)
    {
        JFutureInterfaceBase::operator=(other);
        return *this;
    }

    inline JFuture<void> future(); // implemented in qfuture.h

    void reportResult(const void *, int) { }
    void reportResults(const jvector<void> &, int) { }
    void reportFinished(void * = 0) { JFutureInterfaceBase::reportFinished(); }
};

#endif // JFUTUREINTERFACE_H
